package com.jikangjun.disk.user.control;

import com.jikangjun.disk.email.EmailService;
import com.jikangjun.disk.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/password")
public class PasswordResetController {

    @Autowired
    private UserService userService;

    @Autowired
    private EmailService emailService;

    /**
     * 发送验证码到邮箱
     */
    @PostMapping("/sendCode")
    public Map<String, Object> sendCode(@RequestParam String email, HttpSession session) {
        Map<String, Object> result = new HashMap<>();

        // 检查邮箱是否已注册
        boolean exists = userService.checkEmailExists(email);
        if (!exists) {
            result.put("success", false);
            result.put("msg", "邮箱未注册");
            return result;
        }

        try {
            // 发送验证码（修改：不接收返回值，或根据实际返回值类型调整）
            emailService.sendCode(email, "reset"); // 假设此方法返回void或调整为正确类型

            // 生成验证码并存储到session（如果sendCode方法不返回验证码）
            String code = generateVerificationCode();
            session.setAttribute("resetCode_" + email, code);
            session.setMaxInactiveInterval(60 * 5); // 5分钟有效期

            result.put("success", true);
            result.put("msg", "验证码已发送");
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "发送失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 验证验证码并重置密码
     */
    @PostMapping("/reset")
    public Map<String, Object> resetPassword(
            @RequestParam String email,
            @RequestParam String code,
            @RequestParam String newPassword,
            HttpSession session) {

        Map<String, Object> result = new HashMap<>();

        // 验证验证码
        String storedCode = (String) session.getAttribute("resetCode_" + email);
        if (storedCode == null || !storedCode.equals(code)) {
            result.put("success", false);
            result.put("msg", "验证码无效或已过期");
            return result;
        }

        try {
            // 加密密码
            String encryptedPassword = userService.encryptPassword(newPassword);

            // 修改：使用正确的方法名和参数列表
            boolean updated = userService.updatePasswordByEmail(email, encryptedPassword);
            if (updated) {
                // 清理session中的验证码
                session.removeAttribute("resetCode_" + email);
                result.put("success", true);
                result.put("msg", "密码重置成功");
            } else {
                result.put("success", false);
                result.put("msg", "密码重置失败");
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("msg", "重置失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 生成6位数字验证码
     */
    private String generateVerificationCode() {
        int code = (int) (Math.random() * 900000 + 100000);
        return String.valueOf(code);
    }
}
